<?php
define('captcha_expiration', 300); // 5 min
class Captcha_Model extends CI_Model
{
    public function __construct()
    {
        parent::__construct();
    }

    public function captcha_generate()
    {
        $this->load->helper('captcha');
        $vals = array(
            'img_path' => root_dir() . 'data/captcha/',
            //'img_height' => 30,
            //'img_width' => 120,
            'font_path' => '/data/fonts/cinnamon_cake.ttf',
            'img_url' => root_url().'data/captcha/',
            'expiration' => captcha_expiration,
            'time' => time(),
            'word' => strtoupper(random_string('alpha', 4)),
            );

        $cap = create_captcha($vals);

        $data = array(
            'captcha_time' => $cap['time'],
            'ip_address' => $this->input->ip_address(),
            'word' => $cap['word']);

        $query = $this->db->insert_string('captcha', $data);
        $this->db->query($query);
        return $cap['image'];
    }
    
    public function captcha_check()
    {
        $captcha = isset($_POST['captcha']) ? $this->input->post('captcha') : 0;
        $expiration = time() - captcha_expiration; // Two hour limit
        $this->db->query("DELETE FROM captcha WHERE captcha_time < ".$expiration);
        if ($captcha !== 0) {
            // Then see if a captcha exists:
            $sql = "SELECT COUNT(*) AS count FROM captcha WHERE word = ? AND ip_address = ? AND captcha_time > ?";
            $binds = array($captcha, $this->input->ip_address(), $expiration);
            $query = $this->db->query($sql, $binds);
            $row = $query->row();
            if ($row->count == 0) {
                return false;
            } else {
                return true;
            }    
        } else {
            return false;
        }
    }
}
